package com.paw.restHighLevel.controller;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: lvzihai
 * @date: 2021/5/25
 **/
@Api(tags = "RestHighLevel客户端")
@RestController
public class EsRestHighLevelController {

  @Autowired
  private RestHighLevelClient restHighLevelClient;

  @ApiOperation("search")
  @GetMapping("/search")
  public Object search(){

    SearchRequest searchRequest = new SearchRequest("logs-2021.05.25");
    // 构造条件
    SearchSourceBuilder builder = new   SearchSourceBuilder();

    // 精确匹配
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("appName.keyword","activity");
    TermQueryBuilder termQueryBuilder2 = QueryBuilders.termQuery("level.keyword","ERROR");
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery().filter(termQueryBuilder).filter(termQueryBuilder2);
    builder.query(boolQueryBuilder);
    // 分页
    builder.from();
    builder.size(100);
    builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
    searchRequest.source(builder);
    String result = "";
    try {
      SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
      result = JSON.toJSONString(response);
      System.out.println(JSON.toJSONString(response.getHits()));
    } catch (IOException e) {
      e.printStackTrace();
    }

    return result;
  }
}
